package home.adapter;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.facebook.drawee.view.SimpleDraweeView;

import net.ck.hzq.R;
import net.ck.hzq.WebviewActivity;

import java.util.ArrayList;
import java.util.List;

import Utils.ScreenUtil;
import dao.HomeBannerBean;

public class CenterBannerAdapter1 extends DelegateAdapter.Adapter<CenterBannerAdapter1.BannerViewHolder> {

    private static final String TAG = "BannerAdapter";

    private final Context mContext;

    private List<List<HomeBannerBean>> mData;

    private final int SLEEP_TIME = 3 * 1000;
    private long lastUpdateTime;
    private int currentPosition = 0;
    private final int FIRST_PAGE = 1;
    private final int HANDLE_MSG = 2;

    public CenterBannerAdapter1(Context context) {
        mContext = context;
        mData = new ArrayList<>();
    }

    public void setUpBanner(List<List<HomeBannerBean>> data) {
        mData.clear();
        if (data != null) {
            mData.addAll(data);
        }
        notifyDataSetChanged();
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
        layoutHelper.setMargin(0, ScreenUtil.dip2px(mContext, 15), 0, ScreenUtil.dip2px(mContext, 15));
        return layoutHelper;
    }

    @NonNull
    @Override
    public CenterBannerAdapter1.BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.item_home_center_banner1, parent, false);
        return new CenterBannerAdapter1.BannerViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull final CenterBannerAdapter1.BannerViewHolder holder, int position) {
        if (mData == null && mData.size() == 0) {
            return;
        }
        BannerPagerAdapter adapter = new BannerPagerAdapter();
        holder.viewPager.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what != HANDLE_MSG) {
                    return;
                }
                long intervalTime = 0;
                if (lastUpdateTime > 0) {
                    intervalTime = (System.currentTimeMillis() - lastUpdateTime);
                    if (intervalTime < SLEEP_TIME) {
                        intervalTime = SLEEP_TIME - intervalTime;
                        sendEmptyMessageDelayed(HANDLE_MSG, intervalTime);
                        return;
                    }
                }
                lastUpdateTime = System.currentTimeMillis();
                currentPosition = holder.viewPager.getCurrentItem() + 1;
                resetPosition(currentPosition);
                holder.viewPager.setCurrentItem(currentPosition, false);
                sendEmptyMessageDelayed(HANDLE_MSG, SLEEP_TIME);
            }
        };
        handler.sendEmptyMessageDelayed(HANDLE_MSG, SLEEP_TIME);
        holder.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                resetPosition(i);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    handler.removeMessages(HANDLE_MSG, null);
                    holder.viewPager.setCurrentItem(currentPosition, false);
                    handler.sendEmptyMessageDelayed(HANDLE_MSG, SLEEP_TIME);
                }
            }
        });
    }


    @Override
    public int getItemCount() {
        return 1;
    }

    class BannerViewHolder extends RecyclerView.ViewHolder {
        private ViewPager viewPager;

        private BannerViewHolder(View itemView) {
            super(itemView);
            viewPager = itemView.findViewById(R.id.view_pager);
            viewPager.setPageMargin(ScreenUtil.dip2px(itemView.getContext(), 10));
        }
    }

    private class BannerPagerAdapter extends PagerAdapter {


        @Override
        public int getCount() {
            return Integer.MAX_VALUE;      // 因为需要无限循环，所以这里就不写imageList.size()
        }

        @Override
        public float getPageWidth(int position) {
            return 0.98f;
        }

        /**
         * 获得相应位置上的view
         * container  view的容器，其实就是viewpager自身
         * position   相应的位置
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 给container添加内容
            SimpleDraweeView imageView = new SimpleDraweeView(container.getContext());
            imageView.setScaleType(SimpleDraweeView.ScaleType.FIT_XY);
            if (mData.size() != 0) {
                if (mData.get(position % mData.size()) != null && mData.get(position % mData.size()).size() > 0) {
                    imageView.setImageURI(Uri.parse((mData.get(position % mData.size()).get(0).imgBanner)));
//                Glide.with(container.getContext())
//                        .load(mData.get(index).get(0).imgBanner)
//                        .into(imageView);
                    imageView.setOnClickListener(v -> {
                        WebviewActivity.start(mContext, mData.get(position % mData.size()).get(0).imgPath);

                    });
                }
            }
            container.addView(imageView);
            return imageView;
        }

        /**
         * 判断view和object的对应关系
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 销毁对应位置上的object
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            object = null;
        }
    }

    //重置展示位置
    private void resetPosition(int position) {
        //当前展示的图片等于最后位置的时候，重置到第一张图的位置
        if (position == mData.size() - 1) {
            currentPosition = FIRST_PAGE;
            return;
        }

        //当前位置等于最后一项位置的时候，重置到最后一张图的位置
        if (position == 0) {
            currentPosition = mData.size() - 2;
            return;
        }

        //不是首尾位置，正常顺序展示
        currentPosition = position;
    }


}

